# -*- coding: utf-8 -*-
from PySide import QtCore, QtGui, QtWebKit
from operator import attrgetter

from config import *
from utils import unescape
#from post_widget import PostView


class QWorker(QtCore.QThread):
    
    signal = QtCore.Signal(str)
    signal_update_status_bar = QtCore.Signal(tuple)
    signal_update_progress_bar = QtCore.Signal(int)
    fill_tree_signal = QtCore.Signal(int, int, tuple, int)
    
    def __init__(self, parent = None):
        QtCore.QThread.__init__(self, parent)
        self.func = None
        self.data = None
        self.exc = None
        self.exiting = False
        self.UL_THREADS = UL_THREADS
        self.parent = parent
        self.forum = parent.forum
        self.args = ()
        self.kwargs = {}
        self.disabled_ids = []
        self.signal.connect(self.parent.on_finished)
        self.signal_update_status_bar.connect(self.parent.update_status_bar)
        self.signal_update_progress_bar.connect(self.parent.update_progress_bar)
        self.fill_tree_signal.connect(self.parent.add_tree_item)
        if self.parent._update_target == UPDATE_ALL:
            self.disabled_ids = []
        elif self.parent._update_target == UPDATE_SELECTED:
            self.disabled_ids = [id for id, item in self.parent._forum_cache.items() if not item.checked]
        elif self.parent._update_target == UPDATE_UNSELECTED:
            self.disabled_ids = [id for id, item in self.parent._forum_cache.items() if item.checked]
        #self.disabled_ids = [42, 91]
        #print self.disabled_ids

    def work(self, func, *args, **kwargs):
        self.func = attrgetter(func)(self)
        self.args = args
        self.kwargs = kwargs
        self.start()

    def _update_threads(self):
        for id, f_title in self.UL_THREADS.iteritems():
            if id in self.disabled_ids: continue
            f_data = (0, f_title),
            self.fill_tree_signal.emit(0, id, f_data, TOP_LEVEL)

        forums = self.forum.get_forums_list()
        i = 100 - len(forums) # TODO: later...
        self.signal_update_progress_bar.emit(i)

        for f in  forums:
            f_id, f_title, f_answers, f_bluetime, f_lastauthor, f_threads, f_parentid = f
            f_id = int(f_id)
            f_parentid = int(f_parentid)
            if f_parentid in self.disabled_ids or f_id in self.disabled_ids: continue
            f_title = unicode(unescape(f_title), FORUM_ENCODING)
            #print f_parentid, f_id, f_title, self.disabled_ids
            t_data = (0, f_title), (1, f_threads), (2, f_answers), (3, f_bluetime)
            self.fill_tree_signal.emit(f_parentid, f_id, t_data, FORUM)
            
            for t in self.forum.get_threads_list(f_id):
                t_id, t_title, t_bluetime, t_open1, t_open2, t_answers, t_author, t_author_id, t_lastauthor, t_lastauthor_id, t_undertitle = t
                #print t_id, unicode(unescape(t_title), FORUM_ENCODING), t_bluetime, t_open1, t_open2, t_answers, unicode(unescape(t_author), FORUM_ENCODING), t_author_id, t_lastauthor_id, unicode(unescape(t_undertitle), FORUM_ENCODING)
                t_id = int(t_id)
                if t_id in self.disabled_ids: continue
                t_title = unicode(unescape(t_title), FORUM_ENCODING)
                if t_undertitle: t_title += " (%s)" % unicode(unescape(t_undertitle), FORUM_ENCODING)
                self.signal_update_status_bar.emit((t_title, 0))
                t_data = (0, t_title), (2, t_answers), (3, t_bluetime)
                self.fill_tree_signal.emit(f_id, t_id, t_data, THREAD)
            i += 1
            self.signal_update_progress_bar.emit(i)
        self.signal_update_progress_bar.emit(100)
        self.signal_update_status_bar.emit(('Ready', 0))

    def run(self):
        try:
            self.data = self.func(*self.args, **self.kwargs)
        except Exception, e:
            self.signal.emit(e.message)
        else:
            self.signal.emit('')

    def __del__(self):
        self.exiting = True
        self.wait()
        